﻿namespace Module_Debug
{
    class CRC16
    {
        public CRC16()
        {
        }
        public ushort CalculateCrc16(byte[] buffer, out byte crcHi, out byte crcLo)
        {
            ushort CRC_16 = 0xffff;
            for (int t = 0; t < buffer.Length - 2; t++)
            {

                CRC_16 = (ushort)(CRC_16 ^ (buffer[t] << 8));
                for (int i = 0; i < 8; i++)
                {
                    if (CRC_16 >= 0x8000)            /* b15 is set... */
                        CRC_16 = (ushort)((CRC_16 << 1) ^ 0x1021);    /* rotate and XOR with polynomic */
                    else                          /* b15 is clear... */
                        CRC_16 <<= 1;                  /* just rotate */
                }


            }
            crcHi = (byte)(CRC_16 >> 8);
            crcLo = (byte)(CRC_16);
            return CRC_16;
        }
        public ushort CalculateCrc16Start_Length(byte[] buffer, int StartAddr, int Length, out byte crcHi, out byte crcLo)
        {
            ushort CRC_16 = 0xffff;
            for (int t = StartAddr; t < StartAddr + Length; t++)
            {

                CRC_16 = (ushort)(CRC_16 ^ (buffer[t] << 8));
                for (int i = 0; i < 8; i++)
                {
                    if (CRC_16 >= 0x8000)            /* b15 is set... */
                        CRC_16 = (ushort)((CRC_16 << 1) ^ 0x1021);    /* rotate and XOR with polynomic */
                    else                          /* b15 is clear... */
                        CRC_16 <<= 1;                  /* just rotate */
                }


            }
            crcHi = (byte)(CRC_16 >> 8);
            crcLo = (byte)(CRC_16);
            return CRC_16;
        }

    }
}
